<template>    
    <el-dialog
      style="top: -100px"
      title="投诉"
      :visible.sync="visible"
      width="700px"
      :before-close="handleClose"
      class="announcement-edit-dialog"
    >
      <el-steps :active="active" finish-status="success">
        <el-step title="待处理"></el-step>
        <el-step title="处理中"></el-step>
        <el-step title="已处理"></el-step>
        <el-step title="已关闭"></el-step>
      </el-steps>

      <div>
        <el-form :model="form" :rules="rules" ref="form" style="margin-right:60px" label-width="100px" label-position="right">
          <el-form-item label="投诉标题" prop="title" ref="title">
            <el-input v-model="form.title" placeholder="请输入投诉标题"></el-input>
          </el-form-item>

          <el-form-item label="投诉类型" prop="complaintType" ref="complaintType" class="editor-form-item">
            <el-radio-group v-model="form.complaintType" size="small">
              <el-radio-button :label="0">公共设施</el-radio-button>
              <el-radio-button :label="1">环境卫生</el-radio-button>
              <el-radio-button :label="2">噪音扰民</el-radio-button>
              <el-radio-button :label="3">安全问题</el-radio-button>
              <el-radio-button :label="4">服务质量</el-radio-button>
              <el-radio-button :label="5">其他</el-radio-button>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="投诉内容" prop="content" ref="content" class="editor-form-item">
              <mavon-editor v-model="form.content" :toolbars="toolbars"/>
          </el-form-item>

          <el-form-item label="投诉图片" prop="images" ref="images" class="editor-form-item">
            <el-upload
              class="upload-demo"
              action="http://localhost:7001/ossFile/upload"
              :headers="headers"
              :on-preview="handlePreviewTwo"
              :on-remove="handleRemoveTwo"
              :file-list.sync="fileListTwo"
              list-type="picture"
              :before-upload="beforeUploadTwo"
              :on-success="handleSuccess"
              multiple>
              <el-button style="margin-top: 10px" size="small" type="primary" >点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传 jpg/png 文件，且不超过 500KB</div>
            </el-upload>
          </el-form-item>
          
        </el-form>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button style="margin-top: 12px;" @click="next">下一步</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </span>
    </el-dialog>
  </template>
  
  <script>
import { mavonEditor } from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
import { cloneDeep } from 'lodash';
import { mapState,mapMutations } from "vuex"


  export default {  
    components: {
        mavonEditor,
      },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      formData: {
        type: Object,
        default: () => ({})
      },
      user:{
        type: Object,
        default: () => {}
      },
    },
    data() {
      return {
        headers: {},
        fileListTwo: [],
        active: 0,
        checkAll: false,
        cities: [],
        checkedCities:[],
        isIndeterminate: false,
        disablePublishTime: false,
        flack: false,
        form: {
            complaintType: 0,
            title: '',
            content: '',
            reporterId:'',
            reporterName:'',
            images:'',
            status:0,
            processResult: '',
            processUserId:'',
            processUsername:'',
            statisFaction:"",
            feedback:""
        },
        updateStatus:{
          initialStatus: 0,
        },
        rules: {
          title: [
            { required: true, message: '请输入投诉标题', trigger: 'blur' }
          ],
          content: [
            { required: true, message: '请输入投诉内容', trigger: 'blur' }
          ],
        },
        toolbars: {
            bold: true, // 粗体
            italic: true, // 斜体
            header: true, // 标题
            underline: true, // 下划线
            strikethrough: true, // 中划线
            mark: true, // 标记
            quote: true, // 引用
            ol: true, // 有序列表
            ul: true, // 无序列表
            code: true, // code
            table: true, // 表格
            fullscreen: true, // 全屏编辑
            htmlcode: true, // 展示html源码
            help: true, // 帮助
            /* 1.3.5 */
            undo: true, // 上一步
            redo: true, // 下一步
            trash: true, // 清空
            /* 2.1.8 */
            alignleft: true, // 左对齐
            aligncenter: true, // 居中
            alignright: true, // 右对齐
            /* 2.2.1 */
            subfield: true, // 单双栏模式
            preview: true, // 预览
        }
      }
    },
    created(){
    },
    methods: {
      ...mapMutations("login",["setUser","setUserNull"]),
      next() {
        if (this.active++ > 3) this.active = 0;
      },

      submitForm(form) {
        this.$refs[form].validate((valid) => {
          if (valid) {
            //获取发布范围的IDs
            let receiverIdList = [];
            this.form.receivers.forEach(receiverLabel =>{
                const matchedCity = this.cities.find(city => city.label === receiverLabel);
                if(matchedCity){
                  receiverIdList.push(matchedCity.value);
                }
            })
            //数据处理
            this.form.receiverIds = receiverIdList.join(",");

            if((this.form.id && this.form.status === 1) || (!this.form.id && this.form.status ===1 )){
                // 获取当前日期
                this.form.publishTime = new Date();
            }

            if (this.form.publishTime instanceof Date) {
                this.form.publishTime = this.formatDate(this.form.publishTime);
            }else{
              const dateObj = new Date(this.form.publishTime);
              this.form.publishTime = this.formatDate(dateObj);
            }

            // 提交表单数据
            api.noticeAdd(this.form).then(res =>{
                if(res.type === 'error'){
                    this.$message.error(res.message)
                }else if(res.data.code === 200){
                  this.$message({
                    message: '操作成功',
                    type: 'success'
                  });
                  this.handleClose();
                  location.reload();
                }else{
                  this.$message.error(res.data.message)
                }
            })


            this.handleClose();
          } else {
            this.$message.error('请完善表单信息');
            return false;
          }
        });
      },

      //设置日期格式
      formatDate(date) {
          const year = date.getFullYear();
          const month = String(date.getMonth() + 1).padStart(2, '0');
          const day = String(date.getDate()).padStart(2, '0');
          return `${year}-${month}-${day}`;
      },
      
      handleClose() {
        // 手动清空表单
        this.form = {
              title: '',
              status: 0,
              content: '',
              publishTime: null,
              receivers: []
        };
        // 重置表单验证状态
        this.$refs['form'].resetFields();
        this.$emit('update:visible', false);
        this.$emit('update:title', '新增公告');
        this.$emit('updateFormData', {});
        this.checkAll = false
        this.isIndeterminate = false
      },

      // 预览文件
        handlePreviewTwo(file) {
            const w = window.open("", "_blank", "width=800,height=600,top=100,left=100");

            // 构建 HTML 结构（居中 + 阴影背景）
            const html = `
              <!DOCTYPE html>
              <html>
                <head>
                  <style>
                    body {
                      margin: 0;
                      padding: 0;
                      background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色遮罩 */
                      display: flex;
                      justify-content: center;
                      align-items: center;
                      height: 100vh;
                    }
                    .preview-container {
                      background: white;
                      padding: 10px;
                      border-radius: 4px;
                      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
                    }
                    .preview-container img {
                      max-width: 100%;
                      max-height: 90vh; /* 限制高度，避免超出屏幕 */
                      display: block;
                    }
                  </style>
                </head>
                <body>
                  <div class="preview-container">
                    <img src="${file.url}" />
                  </div>
                </body>
              </html>
            `;

            w.document.write(html);
            w.document.close(); // 确保文档写入完成
          },

        // 移除文件
        handleRemoveTwo(file, fileList) {
          if(this.form.status !== 2){
            this.$message.error('禁止删除图片');
              // 关键：恢复原来的文件列表，避免被清空
            this.$nextTick(() => {
              this.fileListTwo = [...this.fileListTwo];
            });

            return false;
          }
          console.log("删除文件:", file);
          this.fileListTwo = fileList; // 确保 fileListTwo 也更新
        },  

        // 上传前的校验
        beforeUploadTwo(file) {
          const isJPGorPNG = file.type === "image/jpeg" || file.type === "image/png";
          const isLt500KB = file.size / 1024 <= 500; // 500KB

          if(this.fileListTwo.length >= 2){
            this.$message.error('只能上传两张图片!');
            return false;
          } 

          if (!isJPGorPNG) {
            this.$message.error("上传失败：只能上传 JPG/PNG 格式的图片！");
            return false;
          }
          if (!isLt500KB) {
            this.$message.error("上传失败：图片大小不能超过 500KB！");
            return false;
          }

          this.headers = {'token': this.user.token}

          console.log( this.headers)

          return true; // 允许上传
        },

        // 上传成功后添加到 fileListTwo
        handleSuccess(response, file, fileListTwo) {
          this.fileListTwo.push({
            name: response.data.url.split('/').pop(),
            url: response.data.url // 生成本地预览地址
          });
        }
    },
    computed: {
        // 将 Markdown 文本编译为 HTML
        compiledMarkdown() {
            return marked.parse(this.markdownText);
        },
    },
    watch: {
        // 监听 formData 的变化
        formData: {
            handler(newVal) {
                if (newVal && Object.keys(newVal).length > 0) {
                    // 深拷贝 formData 并赋值给 ruleForm
                    this.form = cloneDeep(newVal);
                    this.active = this.form.status + 1
                    console.log(this.form)
                }
            },
            immediate: true, // 立即执行一次
            deep: true, // 深度监听
        },
        // 监听 form.status 的变化
        'form.status': {
            handler(newStatus) {
                
            },
            immediate: true
        },
    },
  }
  </script>
  
  <style scoped>

  .announcement-edit-dialog >>> .el-dialog__body {
    padding: 20px 30px;
  }
  
  .editor-wrapper {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
  }
  
  .editor-toolbar {
    border-bottom: 1px solid #dcdfe6;
    background-color: #f5f7fa;
  }
  
  .editor-content {
    min-height: 300px;
    max-height: 500px;
    overflow-y: auto;
  }
  
  .editor-form-item >>> .el-form-item__content {
    line-height: normal;
  }
  
  .line {
    line-height: 36px;
    color: #909399;
  }
  </style>